package com.example.demo01.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.example.demo01.R;
import com.example.demo01.entity.MainMenu;

import java.util.List;

public class MainMenuAdapter extends BaseAdapter {
    private Context context;
    private List<MainMenu> list;
    private int selectedPosition = 0; //. 默认选中第一个

    //. 设置选中位置
    public void setSelectedPosition(int position) {
        this.selectedPosition = position;
        notifyDataSetChanged();//. 通知数据集改变
    }

    public MainMenuAdapter(Context context, List<MainMenu> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.item_main_bar, parent, false);
            holder = new ViewHolder();
            holder.iv_menu_icon = convertView.findViewById(R.id.iv_menu_icon);
            holder.tv_menu_name = convertView.findViewById(R.id.tv_menu_name);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        MainMenu item = getItem(i);
        holder.iv_menu_icon.setImageResource(item.getIconId());
        holder.tv_menu_name.setText(item.getName());


        //. 根据选中状态设置颜色
        if (i == selectedPosition) {
            holder.iv_menu_icon.setImageResource(item.getSelectedIconId());
            holder.tv_menu_name.setTextColor(ContextCompat.getColor(context, R.color.selected_icon));
        } else {
            holder.iv_menu_icon.setImageResource(item.getIconId());
            holder.tv_menu_name.setTextColor(ContextCompat.getColor(context, R.color.not_icon));
        }

        return convertView;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public MainMenu getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return list.get(i).getId();
    }

    static class ViewHolder {
        ImageView iv_menu_icon;
        TextView tv_menu_name;
    }
}
